<template>
  <div class="container">
    <!-- 顶部按钮区域 -->
    <div class="top-bar">
      <el-input v-model="searchQuery" placeholder="请输入商品名称" clearable class="search-input" ref="searchInput" />
      <!-- 筛选器 -->
      <el-select v-model="priceRange" placeholder="筛选价格" class="price-select">
        <el-option label="全部" value=""></el-option>
        <el-option label="0 - 50" value="0-50"></el-option>
        <el-option label="50 - 100" value="50-100"></el-option>
        <el-option label="100+" value="100+"></el-option>
      </el-select>

      <!-- 排序功能 -->
      <el-select v-model="sortOrder" placeholder="排序" class="sort-select">
        <el-option label="价格升序" value="asc"></el-option>
        <el-option label="价格降序" value="desc"></el-option>
      </el-select>
    </div>

    <!-- 商品展示区域 -->
    <div class="view-toggle">
      <el-button @click="toggleView" :type="viewMode === 'list' ? 'primary' : 'default'">列表模式</el-button>
      <el-button @click="toggleView" :type="viewMode === 'grid' ? 'primary' : 'default'">卡片模式</el-button>
    </div>

    <div class="card-container" v-if="viewMode === 'grid'">
      <el-card class="product-card" v-for="(item, index) in filteredItems" :key="index">
        <div class="image-container">
          <img :src="item.coverpicture || defaultImage" class="card-image" />
        </div>
        <div class="product-info">
          <p class="product-name">{{ item.pname }}</p>
          <p class="product-price">{{ item.price }}￥</p>
          <p class="product-description">{{ item.description || '暂无描述' }}</p>
          <p class="product-stock">库存：{{ item.stock }} 件</p>
          <el-button type="primary" @click="editProduc(item)">编辑</el-button>
          <el-button type="danger" @click="showDeleteDialog(item)">删除</el-button>
        </div>
      </el-card>


      <!-- 删除确认弹窗 -->
      <el-dialog title="确认删除" :visible.sync="deledialogVisible">
        <p style="font-size: 26px;">确定要删除"{{ addProductData.pname }}"吗？删除后不可恢复！</p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="deledialogVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteProduct">确认删除</el-button>
        </span>
      </el-dialog>

    </div>





    <div class="list-container" v-else>
      <el-table :data="filteredItems" border>
        <el-table-column prop="pname" label="商品名称"></el-table-column>
        <el-table-column prop="price" label="价格" sortable></el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column prop="stock" label="库存"></el-table-column>

      </el-table>
    </div>

    <!-- 分页功能 -->
    <div class="pagination">
      <el-pagination @current-change="handlePageChange" :current-page="currentPage" :page-size="pageSize"
        :total="totalItems" layout="prev, pager, next, jumper"></el-pagination>
    </div>

    <!-- 底部按钮区域 -->
    <div class="footer-button">
      <el-button type="primary" size="large" @click="addProduct">新添商品</el-button>
    </div>

    <!-- 新增商品对话框（保留原代码部分） -->
    <el-dialog title="新增商品" :visible.sync="dialogVisible" width="500px">
      <div>
        <el-form :model="addProductData">
          <el-form-item label="商品名称" required>
            <el-input v-model="addProductData.pname" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品描述" required>
            <el-input v-model="addProductData.description" placeholder="请输入商品描述" />
          </el-form-item>
          <el-form-item label="价格" required>
            <el-input-number :min="0" v-model="addProductData.price" placeholder="请输入价格" />
          </el-form-item>
          <el-form-item label="库存" required>
            <el-input-number :min="0" v-model="addProductData.stock" placeholder="请输入库存量" />
          </el-form-item>
          <el-form-item label="类别" required>
          <el-select v-model="addProductData.category" placeholder="请选择商品类别">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
          <el-form-item label="图片" v-if=insert>
            <el-upload action="" list-type="picture-card" :file-list="addProductData.fileList" :auto-upload="false"
              :on-change="fileListChange" :on-remove="fileListRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="aboutProduct">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deleteProduct, updateProduct, selectAllproductsByID, launchProduct } from '@/api/market.ts'

export default {
  data() {
    return {
      searchQuery: '',
      products: [],
      defaultImage: 'https://via.placeholder.com/250x200?text=Product+Image',
      priceRange: '',
      sortOrder: '',  // 排序方式
      currentPage: 1,
      pageSize: 10,
      totalItems: 0,
      dialogVisible: false,
      deledialogVisible: false,  // 控制弹窗的显示与隐藏
      viewMode: 'grid',  // 切换视图模式（'grid' 或 'list'）
      addProductData: {
        pid: '',
        pname: '',
        description: '',
        price: '',
        stock: '',
        category: '',
        fileList: [],
      },
      options: [{
        value: '蔬菜',
        label: '蔬菜'
      }, {
        value: '水果',
        label: '水果'
      }, {
        value: '粮油',
        label: '粮油'
      }, {
        value: '肉蛋',
        label: '肉蛋'
      }, {
        value: '干货',
        label: '干货'
      }],
      insert: true,
    }
  },
  computed: {
    filteredItems() {
      let filteredProducts = this.products;

      // 按价格范围筛选
      if (this.priceRange) {
        const [min, max] = this.priceRange.split('-');
        filteredProducts = filteredProducts.filter(item => {
          const price = parseFloat(item.price);
          return price >= (parseFloat(min) || 0) && (max ? price <= parseFloat(max) : true);
        });
      }

      // 按搜索关键词筛选
      const searchQuery = this.searchQuery.trim().toLowerCase();
      filteredProducts = filteredProducts.filter(item =>
        item.pname.toLowerCase().includes(searchQuery)
      );

      // 排序功能
      if (this.sortOrder) {
        filteredProducts.sort((a, b) => {
          return this.sortOrder === 'asc'
            ? parseFloat(a.price) - parseFloat(b.price)
            : parseFloat(b.price) - parseFloat(a.price);
        });
      }

      return filteredProducts;
    },
  },
  methods: {
    async fetchProducts() {
      try {
        const response = await selectAllproductsByID(JSON.parse(localStorage.getItem('currentUser')).uid);
        if (response && response.data && Array.isArray(response.data.data)) {
          this.products = response.data.data;
          this.totalItems = response.data.data.length;
        } else {
          console.error("商品数据格式不正确", response);
        }
      } catch (error) {
        console.error("获取商品数据失败:", error);
      }
    },
    addProduct() {
      this.addProductData = {
        pid: '',
        pname: '',
        description: '',
        price: '',
        stock: '',
        fileList: [],
      },
        this.dialogVisible = true,
        this.insert = true
    }
    ,
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchProducts();
    },
    fileListChange(file, fileList) {
      console.log("加了一张图")
      this.addProductData.fileList = fileList;
    },
    fileListRemove(file, fileList) {
      this.addProductData.fileList = fileList;
    },


    async aboutProduct() {
      const formData = new FormData();
      if (this.insert) {
        if (this.addProductData.fileList && this.addProductData.fileList.length > 0) {
          formData.append("pic", this.addProductData.fileList[0].raw);
        }
        formData.append("product", JSON.stringify({
          pname: this.addProductData.pname,
          description: this.addProductData.description,
          price: this.addProductData.price,
          stock: this.addProductData.stock,
          category: this.addProductData.category
        }))
        try {
          const response = await launchProduct(formData);
          if (response.data.code === 1) {
            this.$message.success("新增商品成功");
            this.dialogVisible = false;
            this.addProductData = { pname: '', description: '', price: '', stock: '',category:'', fileList: [] };
            this.fetchProducts();
          } else {
            this.$message.error(response.data.message || "新增商品失败");
          }
        } catch (error) {
          console.error("新增商品失败:", error);
          this.$message.error("请求失败，请稍后重试");
        }
      }
      else {
        formData.append("newproduct", JSON.stringify({
          pid: this.addProductData.pid,
          pname: this.addProductData.pname,
          description: this.addProductData.description,
          price: this.addProductData.price,
          stock: this.addProductData.stock
        }))

        try {
          const response = await updateProduct(formData);
          if (response.data.code === 1) {
            this.$message.success("修改商品成功");
            this.dialogVisible = false;
            this.addProductData = { pid: '', pname: '', description: '', price: '', stock: '' };
            this.fetchProducts();
          } else {
            this.$message.error(response.data.message || "修改商品失败");
          }
        } catch (error) {
          console.error("修改商品失败:", error);
          this.$message.error("请求失败，请稍后重试");
        }
      }


    },
    editProduc(item) {
      const formData = new FormData();

      this.dialogVisible = true;
      this.insert = false;
      this.addProductData.pid = item.pid;
      this.addProductData.pname = item.pname;
      this.addProductData.description = item.description;
      this.addProductData.price = item.price;
      this.addProductData.stock = item.stock;


    }
    ,
    // 显示删除确认弹窗
    showDeleteDialog(item) {
      this.addProductData = item;  // 记录当前要删除的商品
      this.deledialogVisible = true;  // 打开弹窗
    },
    // 执行删除操作
    async deleteProduct() {

      try {
        const response = await deleteProduct(this.addProductData.pid);
        if (response.data.code === 1) {
          this.$message.success("删除商品成功");
          this.deledialogVisible = false;
          this.addProductData = { pid: '', pname: '', description: '', price: '', stock: '' };
          this.fetchProducts();
        } else {
          this.$message.error(response.data.message || "删除商品失败");
        }
      } catch (error) {
        console.error("删除商品失败:", error);
        this.$message.error("请求失败，请稍后重试");
      }
    },


    toggleView() {
      this.viewMode = this.viewMode === 'grid' ? 'list' : 'grid';
    }
  },
  mounted() {
    this.fetchProducts();
    this.$nextTick(() => {
      this.$refs.searchInput.focus();  // 自动聚焦搜索框
    });
  },
}
</script>

<style scoped>
.container {
  padding: 20px;
}

.top-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.price-select,
.sort-select {
  width: 150px;
  margin-left: 20px;
}

.view-toggle {
  margin-bottom: 10px;
}

.card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.product-card {
  width: 250px;
  box-sizing: border-box;
}

.image-container {
  height: 200px;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.card-image {
  width: 100%;
  object-fit: cover;
}

.product-info {
  padding: 10px;
  text-align: center;
}

.product-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.product-price {
  font-size: 14px;
  color: #e53935;
  margin-bottom: 5px;
}

.product-description {
  font-size: 12px;
  color: #757575;
  margin-bottom: 10px;
}

.product-stock {
  font-size: 12px;
  color: #388e3c;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.footer-button {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
